<template xmlns="http://www.w3.org/1999/html">
  <div class="page-container">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="全部用户" name="0">
      </el-tab-pane>
      <el-tab-pane label="微信公众号用户" name="1">
      </el-tab-pane>
      <el-tab-pane label="微信小程序用户" name="2">
      </el-tab-pane>
      <el-tab-pane label="H5用户" name="3">
      </el-tab-pane>
    </el-tabs>

    <el-form :model="userForm" inline >
      <el-form-item label="用户搜索">
        <el-input v-model="userForm.name" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item style="padding-left: 700px">
        <el-button type="primary" >搜索</el-button>
        <el-button>重置</el-button>
        <el-button v-if="aa===1" @click="toggleVisibility">展开<el-icon><ArrowDown /></el-icon></el-button>
      </el-form-item>

      <div v-if="isVisible">
        <el-form-item label="用户等级">
          <el-select v-model="userForm.level" placeholder="请选择" style="width:200px">
            <el-option label="普通会员" :value="1"></el-option>
            <el-option label="黄铜会员" :value="2"></el-option>
            <el-option label="白银会员" :value="3"></el-option>
            <el-option label="黄金会员" :value="4"></el-option>
            <el-option label="钻石会员" :value="5"></el-option>
            <el-option label="大师会员" :value="6"></el-option>
            <el-option label="顶级会员" :value="7"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户分组">
          <el-select v-model="userForm.gro" placeholder="请选择" style="width:200px">
            <el-option label="初级会员" :value="1"></el-option>
            <el-option label="中级会员" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <br>
        <el-form-item label="用户标签">
          <el-select v-model="userForm.biao" placeholder="请选择" style="width:200px">
            <el-option label="中级" :value="1"></el-option>
            <el-option label="高级" :value="2"></el-option>
            <el-option label="黄金" :value="3"></el-option>
            <el-option label="超级" :value="4"></el-option>
            <el-option label="钻石" :value="5"></el-option>
          </el-select>
        </el-form-item>


        <br>
        <el-form-item label="性别">
          <div style="margin-top: 10px">
            <el-radio-group v-model="userForm.sex">
              <el-radio-button label="全部" :value="-1" />
              <el-radio-button label="男" :value="0" />
              <el-radio-button label="女" :value="1" />
              <el-radio-button label="未知" :value="2" />
              <el-radio-button label="保密" :value="3" />
            </el-radio-group>
          </div>

          <el-button v-if="aa===0" style="margin-left: 840px" @click="toggleVisibility">收起<el-icon><ArrowUp /></el-icon></el-button>
        </el-form-item>
      </div>
    </el-form>

    <el-table :data="tableData" >
      <el-table-column label="ID" prop="id"></el-table-column >
      <el-table-column label="头像" prop="avatar">

      </el-table-column>
      <el-table-column label="姓名" prop="name">
        <template #default="score">
          <span>{{score.row.name}}</span>
          <span v-if="score.row.sex===0">男</span>
          <span v-if="score.row.sex===1">女</span>
          <span v-if="score.row.sex===2">未知</span>
          <span v-if="score.row.sex===3">保密</span>
        </template>
      </el-table-column>

      <el-table-column label="用户等级" prop="level">
        <template #default="score">
          <span v-if="score.row.level===0">-</span>
          <span v-if="score.row.level===1">普通会员</span>
          <span v-if="score.row.level===2">黄铜会员</span>
        </template>
      </el-table-column>
      <el-table-column label="分组" prop="gro">
        <template #default="score">
          <span v-if="score.row.gro===1">初级会员</span>
          <span v-if="score.row.gro===2">中级会员</span>
        </template>
      </el-table-column>
      <el-table-column label="推荐人" prop="commitId">
        <template #default="score">
          <span v-if="score.row.commitId===score.row.id">{{score.row.name}}</span>
          <span v-if="score.row.commitId===null ">无</span>

        </template>
      </el-table-column>

      <el-table-column label="电话号码" prop="phone">
        <template #default="score">
          <!--            <span> {{ maskPhoneNumber(score.row.phone) }}</span>-->
          <span> {{ maskPhoneNumber(score.row.phone) }}</span>
        </template>
      </el-table-column>



      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleOpen(scope.row)">修改</el-button>
          <el-button link type="primary" size="small" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination size="small" v-model:page="userForm.pageNum"
                   v-model:limit="userForm.pageSize"
                   layout="prev, pager, next" :total="total"
                   :current-page="currPageCount" @current-change="handleCurrentChange"/>

    <el-dialog
        v-model="dialogVisible"
        title="编辑用户"
        width="50%"
        :before-close="handleClose"
    >
      <el-form :model="userFormData" inline ref="userFormDataRef" label-width="120" :rules="rules">
        <el-row>
          <el-col :span="userFormData.id?24:12">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="userFormData.userName" placeholder="填写角色名称" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!userFormData.id">
            <el-form-item label="登录密码" prop="passWord">
              <el-input type="password" show-password v-model="userFormData.passWord"
                        placeholder="填写登录密码"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-radio value="1" v-model="userFormData.sex">男</el-radio>
              <el-radio value="0" v-model="userFormData.sex">女</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号">
              <el-input v-model="userFormData.phone" placeholder="填写手机号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="用户角色">
              <el-select v-model="userFormData.roles" multiple placeholder="选择角色" style="width:200px">
                <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitForm">
				提交
				</el-button>
			</span>
      </template>
    </el-dialog>

    <el-dialog
        v-model="dialogUpdateVisible"
        title="修改密码"
        :before-close="handleUpdateClose"
        style="width: 30%;"
    >
      <el-form :model="passwordFormData" inline ref="passwordFormDataRef" label-width="120">
        <el-form-item label="新密码">
          <el-input v-model="passwordFormData.newPassWord" placeholder="输入新密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitPassForm">
				提交
				</el-button>
			</span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="makeTableDemo">
import {defineAsyncComponent, reactive, ref, onMounted} from 'vue';
import {ElMessageBox, ElMessage} from 'element-plus';
import {pageList, addOrUpdate, userDelById, updatePass} from '@/api/system/user'
import {rolePageList} from '@/api/system/role';

// 引入组件
// const Table = defineAsyncComponent(() => import('@/components/pageTable.vue'));
// const TableSearch = defineAsyncComponent(() => import('@/components/pageSearch.vue'));

const maskPhoneNumber = (phoneNumber:String) => {
  if (!phoneNumber) return ""
  return  phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};

const isVisible=ref(false)
const aa=ref(1)
const toggleVisibility=()=>{
  if (aa.value===1){
    isVisible.value=true
    aa.value=0
  }else {
    isVisible.value=false
    aa.value=1
  }

}
onMounted(() => {

});
// 定义变量内容
const passwordFormData = ref({
  id: null,
  newPassWord: null
})
const activeName = ref('0')

function handleClick(value: any) {
  console.log(value)
  activeName.value = value
}

const dialogVisible = ref(false)
const dialogUpdateVisible = ref(false)
const userFormDataRef = ref(null)
const total = ref(0)
const currPageCount = ref(0)
const userForm = reactive({
  name: '',
  level:'',
  gro:'',
  biao:'',
  sex:'',
  pageSize: 10,
  pageNum: 1
});

const userFormData = reactive({
  id: null,
  userName: null,
  passWord: null,
  sex: null,
  roles: [],
  phone: null
})

const tableData = ref([])
const rules = ref({
  userName: [
    {required: true, message: '请输入用户名', trigger: 'blur'}
  ],
  passWord: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ]
})

//修改密码
function submitPassForm() {
  updatePass(passwordFormData.value).then((resp: any) => {
    if (resp.code == 200) {
      ElMessage({message: '修改成功', type: 'success',})
      dialogUpdateVisible.value = false
      userList()
    }

  })
}

function handleOpenPass(row: any) {
  dialogUpdateVisible.value = true
  passwordFormData.value.id = row.id
}

//关闭修改密码窗口
function handleUpdateClose() {
  dialogUpdateVisible.value = false
}

function deleteUser(id: Number) {
  ElMessageBox.confirm(
      '确认要删除用户吗?',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        userDelById(id).then((resp: any) => {
          ElMessage({message: '删除成功', type: 'success',})
          userList()
        })
      })

}

//修改状态
function changeStatus(row: any) {
  addOrUpdate(row).then((resp: any) => {
    ElMessage({message: '提交成功', type: 'success',})
    handleClose()
    userList()
    resertFrom()
  })
}

//提交
function submitForm() {
  userFormDataRef.value.validate((valid) => {
    if (valid) {
      addOrUpdate(userFormData).then((resp: any) => {
        ElMessage({message: '提交成功', type: 'success',})
        handleClose()
        userList()
        resertFrom()
      })
    }
  })

}

function resertFrom() {
  Object.assign(userFormData, {
    id: null,
    userName: null,
    passWord: null,
    sex: null,
    roles: [],
    phone: null
  });
}

//打开弹出框
function handleOpen(val: any) {
  dialogVisible.value = true
  resertFrom()
  if (val) {
    Object.assign(userFormData, val);
  }
}

// function roleName(val: any) {
//   console.log(val[0])
//   if (val) {
//     let roleName = '';
//     for (let i = 0; i < roleList.value.length; i++) {
//       console.log(roleList.value[i].id)
//       for (let j = 0; j < val.length; j++) {
//         if (roleList.value[i].id == val[j]) {
//           roleName += roleList.value[i].name + ','
//           console.log(roleName)
//         }
//       }
//     }
//     return roleName;
//   }
// }

//关闭弹出框
function handleClose() {
  dialogVisible.value = false
}

function userList() {
  pageList(userForm).then((resp: any) => {

    tableData.value = resp.data.records
    total.value = resp.data.total
    currPageCount.value = resp.data.current
  })
}

//点击分页
function handleCurrentChange(val: any) {
  console.log(`当前页: ${val}`);
  userForm.pageNum = val
  userList()
}

const roleList = ref([])

function getRoleList() {
  rolePageList({pageSize: 100, pageNum: 1}).then(((resp: any) => {
    console.log(resp)
    roleList.value = resp.data.records

  }))
};
// 页面加载时
onMounted(() => {
  getRoleList()
  userList()
});

</script>

<style scoped lang="scss">
.page-container {
  height: 100%;
  background-color: #fff;
  padding: 10px 10px;
  display: flex;
  flex-direction: column;

  .pageContent {
    height: calc(100% - 140px);
    flex: 1;
  }
}

</style>
